const app = getApp()
import {
    meetingRoomDict,
    meetingRoomListRq,
    getTodayReservations
} from "../../../api/meeting/meetingRoom.js"

import Notify from '@vant/weapp/notify/notify';

// 存储API返回的预约数据
let roomBookingData = {};

Page({

    /**
     * 页面的初始数据
     */
    data: {
        IMG_NAME: app.IMG_NAME,
        roomDataList: [],
        timeHours: ['8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21','22','23'],
        queryParam: {
            meetingTypeDict: {
                list: [],
                value: null,
            },
            personDict: {
                list: [],
                value: null,
            },
            itemDict: {
                list: [],
                value: null,
                title: '设备'
            },
            shapeDict: {
                list: [],
                value: null,
            },
        },
        selectedDate: '',
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 页面初始化 options为页面跳转所带来的参数
        if (options.name) {
            wx.setNavigationBarTitle({
                title: options.name
            })
        }

        // 初始化数据
        this.initDate();
        this.initData();
    },

    // 初始化日期
    initDate: function () {
        const now = new Date();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        
        this.setData({
            selectedDate: `${month}月${day}日`
        });
    },

    /**
     * 获取预约数据
     */
    fetchReservationData: function () {
        this.setData({
            isLoading: true
        });

        wx.showLoading({
            title: '加载数据中...',
        });

        // 获取当前选择的日期格式化为YYYY-MM-DD
        const now = new Date();
        const year = now.getFullYear();
        let dateStr = this.data.selectedDate || '';
        dateStr = dateStr.replace('月', '-').replace('日', '');
        const formattedDate = `${year}-${dateStr}`;

        // 使用getTodayReservations API获取数据
        getTodayReservations({
            date: formattedDate
        }).then(res => {
            console.log('getTodayReservations 原始返回数据:', res);
            if (res && res.code === 0) {
                // 直接使用API返回的数据，确保数据结构正确
                roomBookingData = res.data || {};
                console.log('解析后的预约数据:', JSON.stringify(roomBookingData));
                
                // 检查数据结构是否正确
                Object.keys(roomBookingData).forEach(roomId => {
                    const roomData = roomBookingData[roomId];
                    console.log(`会议室 ${roomId} 的原始预约数据:`, roomData);
                    
                    // 确保myBookings和otherBookings是数组
                    if (!Array.isArray(roomData.myBookings)) {
                        console.warn(`会议室 ${roomId} 的 myBookings 不是数组，修正为空数组`);
                        roomData.myBookings = [];
                    }
                    
                    if (!Array.isArray(roomData.otherBookings)) {
                        console.warn(`会议室 ${roomId} 的 otherBookings 不是数组，修正为空数组`);
                        roomData.otherBookings = [];
                    }
                });
            } else {
                console.error('获取预约数据失败:', res);
                Notify({ type: 'danger', message: '获取预约数据失败' });
                roomBookingData = {};
            }
        }).catch(err => {
            console.error('请求预约数据失败:', err);
            Notify({ type: 'danger', message: '网络请求失败' });
            roomBookingData = {};
        }).finally(() => {
            wx.hideLoading();
            this.setData({
                isLoading: false
            });
            // 生成时间槽
            this.generateTimeSlots();
        });
    },

    // 初始化数据
    initData() {
        let _this = this;
        // 1.会议室类型，2.人数，3.会议室设备，4.形式
        meetingRoomDict("1").then(res => {
            console.log('meetingRoomDict("1")', res);
            // 封装参数
            let list = res.roomContents.map(item => {
                return {
                    text: item.typeName,
                    value: item.typeValue
                }
            })
            list = [{
                text: "类型",
                value: null
            }, ...list]
            // 赋值参数
            let queryParam = _this.data.queryParam;
            queryParam.meetingTypeDict.list = list;
            _this.setData({
                queryParam
            })
            console.log('meetingRoomDict("1")=>', list);
        })
        meetingRoomDict("2").then(res => {
            console.log('meetingRoomDict("2")', res);
            // 封装参数
            let list = res.roomContents.map(item => {
                return {
                    text: item.capacityNum + '人',
                    value: item.capacityNum
                }
            })
            list = [{
                text: "人数",
                value: null
            }, ...list]
            // 赋值参数
            let queryParam = _this.data.queryParam;
            queryParam.personDict.list = list;
            _this.setData({
                queryParam
            })
            console.log('meetingRoomDict("2")=>', list);
        })
        meetingRoomDict("3").then(res => {
            console.log('meetingRoomDict("3")', res);
            // 封装参数
            let list = res.roomItem.map(item => {
                return {
                    text: item.name,
                    value: item.id
                }
            })
            // 赋值参数
            let queryParam = _this.data.queryParam;
            queryParam.itemDict.list = list;
            _this.setData({
                queryParam
            })
            console.log('meetingRoomDict("3")=>', list);
        })
        meetingRoomDict("4").then(res => {
            console.log('meetingRoomDict("4")', res);
            // 封装参数
            let list = res.roomContents.map(item => {
                return {
                    text: item.shape,
                    value: item.shape
                }
            })
            list = [{
                text: "形式",
                value: null
            }, ...list]
            // 赋值参数
            let queryParam = _this.data.queryParam;
            queryParam.shapeDict.list = list;
            _this.setData({
                queryParam
            })
            console.log('meetingRoomDict("4")=>', list);
        })

        // 数据-会议室列表
        this.meetingRoomList()
    },

    // 查询条件变动
    dictChange(e) {
        console.log('dictChange', e);
        let queryParam = this.data.queryParam;
        queryParam[e.currentTarget.dataset.type].value = e.detail;
        this.setData({
            queryParam
        })
        // 数据-会议室列表
        this.meetingRoomList()
    },

    // 设备-多选
    dictSwitchChange(e) {
        console.log('dictSwitchChange', e);
        let select = e.detail;
        let name = e.currentTarget.dataset.name;
        let id = e.currentTarget.dataset.id;
        let queryParam = this.data.queryParam;
        queryParam.itemDict.list = queryParam.itemDict.list.map(item => {
            if (item.value == id) {
                item.select = select;
            }
            return item
        })
        // 计算选择数量
        let selectCount = queryParam.itemDict.list.filter(item => item.select).length;
        console.log('selectCount', selectCount);
        if (selectCount > 0) {
            queryParam.itemDict.title = '设备+' + selectCount;
        } else {
            queryParam.itemDict.title = '设备';
        }
        this.setData({
            queryParam
        })
        // 数据-会议室列表
        this.meetingRoomList()
    },
    // 设备多选收起
    itemDictConfirm() {
        this.selectComponent('#itemSelect').toggle();
    },

    // 数据-会议室列表
    meetingRoomList() {
        let _this = this;
        let queryParam = _this.data.queryParam;
        let roomItemList = queryParam.itemDict.list.filter(item => item.select).map(item => {
            return {
                "id": item.value,
                "name": item.text
            }
        })
        let param = {
            "type": queryParam.meetingTypeDict.value,
            "capacityNum": queryParam.personDict.value,
            "roomItemList": roomItemList,
            "shape": queryParam.shapeDict.value,
        }
        // 会议室列表数据
        meetingRoomListRq(param).then(res => {
            console.log('meetingRoomListRq', res);
            let roomDataList = res.rows.map(item => {
                if (item.indoorPicUrl) {
                    try {
                        item.indoorPicUrlFirst = JSON.parse(item.indoorPicUrl)[0].url
                    } catch (error) {
                        console.log(`JSON error : ${error}`);
                    }
                }
                return item
            })
            _this.setData({
                roomDataList
            }, () => {
                // 设置完会议室列表后，获取预约数据
                this.fetchReservationData();
            })
        })
    },

    // 日期选择处理
    onDateChange: function (e) {
        const dateValue = e.detail.value; // 格式: YYYY-MM-DD
        const [year, month, day] = dateValue.split('-');
        
        this.setData({
            selectedDate: `${month}月${day}日`
        });

        // 重新获取对应日期的预约数据
        this.fetchReservationData();
    },

    // 会议室
    jumpMeetingRoom(e) {
        console.log('jumpMeetingRoom', e);
        if (e.currentTarget.dataset.id == 47) {
            Notify({
                type: 'danger',
                message: '内部会议室不可预约',
                duration: 3 * 1000,
            });
            return 
        }
        // 跳转预约详情
        wx.navigateTo({
            url: "/pages/meeting/meetingRoom/meetingRoom?id=" + e.currentTarget.dataset.id,
        })
    },
    
    /**
     * 拨打电话
     */
    makeCall: function (e) {
        e.stopPropagation(); // 阻止点击事件冒泡
        const phone = e.currentTarget.dataset.phone;
        if (!phone) {
            Notify({ type: 'warning', message: '没有可用的电话号码' });
            return;
        }
        
        wx.makePhoneCall({
            phoneNumber: phone,
            fail(err) {
                Notify({ type: 'danger', message: '拨打电话失败' });
                console.error('拨打电话失败', err);
            }
        });
    },

    /**
     * 查看位置
     */
    viewLocation: function (e) {
        e.stopPropagation(); // 阻止点击事件冒泡
        const location = e.currentTarget.dataset.location;
        Notify({ type: 'primary', message: `位置: ${location}` });
        // 这里可以实现导航或地图显示功能
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /**
     * 生成时间槽占用数据
     */
    generateTimeSlots: function () {
        // 获取当前时间，用于确定哪些时段不可预约
        const now = new Date();
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        const currentDateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
        const selectedDateStr = this.data.selectedDate ? this.data.selectedDate.replace('月', '-').replace('日', '') : "";
        const selectedDateFull = `${now.getFullYear()}-${selectedDateStr}`;
        
        // 检查是否是今天的日期
        const isToday = currentDateStr === selectedDateFull;
        
        // 详细输出调试信息
        console.log('生成时间槽，当前日期：', currentDateStr);
        console.log('选择的日期：', selectedDateFull);
        console.log('是今天吗？', isToday);
        console.log('会议室列表：', this.data.roomDataList.map(room => `${room.id} - ${room.roomName || ''}`));
        console.log('预约数据完整对象：', roomBookingData);
        
        const roomDataList = this.data.roomDataList.map(room => {
            // 获取此会议室的预定模式
            // 尝试使用room.id查找预定数据
            const roomId = String(room.roomName); // 确保转换为字符串类型作为键
            const pattern = roomBookingData[roomId] || { myBookings: [], otherBookings: [] };
            
            console.log(`会议室 ${roomId} (${room.roomName || ''}) 的预约数据:`, JSON.stringify(pattern));
            
            // 生成时间槽 - 使用半小时为单位
            const timeSlots = [];
            
            // 从8点到23点，生成每半小时的时间槽
            // 例如 8:00-8:30, 8:30-9:00, 9:00-9:30...
            for (let i = 8; i <= 23; i++) {
                for (let minute = 0; minute < 60; minute += 30) {
                    // 生成时间段标识，格式为 "HH:MM"
                    const timeStr = formatTimePoint(i, minute);
                    const nextTimeStr = minute === 0 ? 
                                        formatTimePoint(i, 30) : 
                                        formatTimePoint(i + 1, 0);
                    const timeSlotId = `${timeStr}-${nextTimeStr}`;
                    
                    // 检查此时间段是否已过期
                    let isPastTime = false;
                    if (isToday) {
                        if (i < currentHour || (i === currentHour && minute < currentMinute)) {
                            isPastTime = true;
                        }
                    }
                    
                    // 创建半小时时间值
                    // API使用整数表示当前小时的整点开始
                    // 10 表示10:00-10:30, 10.5 表示10:30-11:00
                    const timeValue = minute === 0 ? i : i + 0.5;
                    
                    // 确保预约数据是数组
                    const myBookings = Array.isArray(pattern.myBookings) ? pattern.myBookings : [];
                    const otherBookings = Array.isArray(pattern.otherBookings) ? pattern.otherBookings : [];
                    
                    // 检查时间段是否被预定，使用精确的数值比较
                    const bookedByMe = myBookings.some(t => Math.abs(t - timeValue) < 0.01);
                    const bookedByOthers = otherBookings.some(t => Math.abs(t - timeValue) < 0.01);
                    
                    // 调试输出时间槽的匹配情况
                    if (bookedByMe || bookedByOthers || (roomId === "101" && (timeValue === 10 || timeValue === 10.5))) {
                        console.log(`会议室 ${roomId} 时间槽 ${timeSlotId} (值=${timeValue}): ` +
                            `我的预定=${bookedByMe} (匹配=${myBookings.includes(timeValue)}, 实际值=${myBookings}), ` +
                            `他人预定=${bookedByOthers} (匹配=${otherBookings.includes(timeValue)}, 实际值=${otherBookings})`);
                    }
                    
                    // 计算时间槽的位置
                    // 总共有 32 个半小时时间段 (8:00-24:00)
                    // 每个时间段宽度为 100/16 = 6.25% (对应整点刻度)
                    // 每个半小时时间段宽度为 3.125%
                    const slotIndex = (i - 8) * 2 + (minute === 0 ? 0 : 1);
                    // 调整位置以确保与时间刻度完美对齐
                    const position = `${slotIndex * 3.2}%`;
                    const width = "3.2%"; // 设置固定宽度确保一致性
                    
                    timeSlots.push({
                        time: i,
                        minute: minute,
                        timeSlotId: timeSlotId,
                        timeValue: timeValue,
                        available: !isPastTime && !bookedByMe && !bookedByOthers,
                        isPastTime: isPastTime && !bookedByMe && !bookedByOthers, // 仅当没有被预约时才显示为过期灰色
                        bookedByMe: bookedByMe, // 无论是否过期，都显示蓝色
                        bookedByOthers: bookedByOthers, // 无论是否过期，都显示橙色
                        position: position,
                        width: width
                    });
                }
            }
            
            return { ...room, timeSlots };
        });

        this.setData({ roomDataList });
        console.log('时间槽生成完成，会议室数量：', roomDataList.length);
        
        // 检查第一个会议室的时间槽是否正确生成
        if (roomDataList.length > 0) {
            const firstRoom = roomDataList.find(room => String(room.id) === "101") || roomDataList[0];
            if (firstRoom) {
                // 查找10点和10:30的时间槽
                const relevantSlots = firstRoom.timeSlots.filter(slot => 
                    slot.timeValue === 10 || slot.timeValue === 10.5);
                
                console.log(`会议室 ${firstRoom.id} 的关键时间槽:`, 
                    relevantSlots.map(slot => ({
                        timeSlotId: slot.timeSlotId,
                        timeValue: slot.timeValue,
                        bookedByMe: slot.bookedByMe,
                        bookedByOthers: slot.bookedByOthers
                    }))
                );
            }
        }
    }
})

// 辅助函数 - 格式化时间点为 "HH:MM" 格式
function formatTimePoint(hour, minute) {
    return `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
}

// 辅助函数 - 格式化时间范围为 "HH:MM-HH:MM" 格式
function formatTimeRange(startHour, startMinute, endHour, endMinute) {
    const formatHour = (hour) => hour.toString().padStart(2, '0');
    const formatMinute = (minute) => minute.toString().padStart(2, '0');
    return `${formatHour(startHour)}:${formatMinute(startMinute)}-${formatHour(endHour)}:${formatMinute(endMinute)}`;
}